#!/usr/bin/env python
# -*-coding:utf-8-*-
# @Time : 2021/9/18 16:22
# @Author : Li Yan
import os
import shutil

from flask import Blueprint, request, current_app, make_response

from utils.file_tool import new_name

getfile = Blueprint('getfile', __name__)


@getfile.post('/getfile')
def get_file():
    file = request.files['file']
    filename = file.filename
    _uuid = request.form.get('_uuid')
    src_file = _uuid + '.uploading'

    src_path = os.path.join(current_app.config['TMP_FOLDER'], src_file)

    removing_file = os.path.join(current_app.config['TMP_FOLDER'], _uuid + '.removing')
    if os.path.isfile(removing_file):
        os.remove(removing_file)
        os.remove(src_path)
        return make_response(('Size mismatch', 500))

    current_chunk = int(request.form['dzchunkindex'])

    with open(src_path, 'ab') as f:
        f.seek(int(request.form['dzchunkbyteoffset']))
        f.write(file.stream.read())

    total_chunks = int(request.form['dztotalchunkcount'])
    if current_chunk + 1 == total_chunks:
        if os.path.getsize(src_path) != int(request.form['dztotalfilesize']):
            return make_response(('Size mismatch', 500))
        else:
            dst_path = os.path.join(current_app.config['TMP_FOLDER'], new_name(filename, _uuid))
            shutil.move(src_path, dst_path)
    return make_response(('Chunk upload successful', 200))
